package com.nio;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

public class DatagramChannelDemo {
    @Test
    public void sendMessDemo() throws Exception {
        DatagramChannel server = DatagramChannel.open();
        InetSocketAddress address = new InetSocketAddress(10086);
        while (true){
            ByteBuffer byteBuffer = ByteBuffer.wrap("发送消息了".getBytes("UTF-8"));
            server.send(byteBuffer, address);
            System.out.println("已经发送完了");
            Thread.sleep(1000);
        }
    }

    @Test
    public void receiveMess() throws Exception {
        // 打开DatagramChannel
        DatagramChannel receiveChannel = DatagramChannel.open();
        InetSocketAddress address = new InetSocketAddress(9999);
        // 绑定
        receiveChannel.bind(address);
        // buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (true){
            byteBuffer.clear();
            SocketAddress receive = receiveChannel.receive(byteBuffer); // 接收
            byteBuffer.flip(); // 读写模式转换
            System.out.println(receive.toString());
            System.out.println(Charset.forName("UTF-8").decode(byteBuffer));
        }
    }
}
